import path from 'path';
import Express from 'express';
import React from 'react';

import {createStore} from 'redux';
import {Provider} from 'react-redux';

import reducers from './reducers'
import App from './App';
import {renderToString} from 'react-dom/server'

const app = Express();
const port = 3009;

app.use(Express.static(path.join(__dirname, 'public')));
// 每当收到请求时都会触发
app.use(handleRender);

// 接下来会补充这部分代码
function handleRender(req, res) { /* ... */
    // 创建新的 Redux store 实例
    const store = createStore(reducers, {user: {name: 'SkyFucker001', age: 10}});
    // const logger = createLogger();
    // const store = createStore(reducers, preloadedState, applyMiddleware(thunkMiddleware, logger));

    // 把组件渲染成字符串
    const html = renderToString(
        <Provider store={store}>
            <App />
        </Provider>
    )

    // 从 store 中获得初始 state
    const preloadedState = store.getState();

    // 把渲染后的页面内容发送给客户端
    var html_ = renderFullPage(html, preloadedState);
    res.send(html_);
}

function renderFullPage(html, preloadedState) { /* ... */
    return `
    <!doctype html>
    <html>
      <head>
        <title>Redux Universal Example</title>
      </head>
      <body>
        <div id="app">${html}</div>
        <script>
          window.__INITIAL_STATE__ = ${JSON.stringify(preloadedState)}
        </script>
        <script src="/bundle.js"></script>
      </body>
    </html>
    `
}

app.listen(port);